package com.yida.gateway.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.config.ResourceHandlerRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;

import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

/**
 * 聚合系统接口
 * 
 * @author yida
 */
@Component
@Primary
public class SwaggerProvider implements SwaggerResourcesProvider, WebFluxConfigurer {
    /**
     * Swagger2默认的url后缀
     */
    public static final String SWAGGER2URL = "/v2/api-docs";

    /**
     * 网关路由
     */
    @Lazy
    @Autowired
    private RouteLocator routeLocator;

    @Autowired
    private GatewayProperties gatewayProperties;

    /**
     * 网关应用名称
     */
    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 聚合其他服务接口
     * 
     * @return
     */
    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resourceList = new ArrayList<>();
        List<String> routes = new ArrayList<>();
        // 获取网关中配置的route
        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
        gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
            .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
                .filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
                .filter(predicateDefinition -> !"yida-auth".equalsIgnoreCase(routeDefinition.getId())).forEach(
                    predicateDefinition -> resourceList.add(swaggerResource(routeDefinition.getId(), predicateDefinition
                        .getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", SWAGGER2URL)))));
        return resourceList;
    }

    // /* 重构聚合接口集成knife4j
    // *
    // *
    // * @return
    // */
    // @Override
    // public List<SwaggerResource> get()
    // {
    // //接口资源列表
    // List<SwaggerResource> resources = new ArrayList<>();
    // //服务名称列表
    // List<String> routeHosts = new ArrayList<>();
    // // 获取所有可用的应用名称
    // routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
    // .filter(route -> !applicationName.equals(route.getUri().getHost()))
    // .subscribe(route -> routeHosts.add(route.getUri().getHost()));
    // //去重，多负载服务只添加一次
    // Set<String> existsServer = new HashSet<>();
    // routeHosts.forEach(host -> {
    // // 拼接url
    // String url = "/" + host + SWAGGER2URL;
    // //不存在则添加
    // if (!existsServer.contains(url)) {
    // existsServer.add(url);
    // SwaggerResource swaggerResource = new SwaggerResource();
    // swaggerResource.setUrl(url);
    // swaggerResource.setName(host);
    // resources.add(swaggerResource);
    // }
    // });
    // return resources;
    // }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** swagger-ui 地址 */
        registry.addResourceHandler("/swagger-ui/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
    }

}
